package Datastruct.BinarySort;

import kotlin.reflect.jvm.internal.impl.descriptors.Visibilities;

public class Node {

    public int value;

    public Node left;
    public Node right;

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    //添加结点
    public void add(Node node) {
        if (node == null) {
            return;
        }
        //传入的值与当前结点的关系
        if (node.value < this.value) {
            if (this.left == null) {
                this.left = node;
            } else {
                this.left.add(node);
            }
        } else {
            if (this.right == null) {
                this.right = node;
            } else {
                this.right.add(node);
            }
        }
    }

    /**
     * 中序遍历     关键码值递增
     */
    public void inOrder() {
        if (this.left != null) {
            this.left.inOrder();
        }
        System.out.println(this);
        if (this.right != null) {
            this.right.inOrder();
        }
    }

    //查询某一个结点
    public Node selectByval(int val) {
        if (this.value == val) {
            return this;
        } else if (this.value > val) {
            //查左子树
            if (this.left == null) {
                return null;
            } else {
                return this.left.selectByval(val);
            }
        } else {
            //查右子树
            if (this.right == null) {
                return null;
            }
            return this.right.selectByval(val);
        }
    }

    /**
     * @param val 删除结点的关键码值
     * @return 删除结点的父结点对象
     */
    public Node selectByparent(int val) {
        if ((this.left != null && this.left.value == val) || (this.right != null && this.right.value == val)) {
            return this;
        } else {
            if (val < this.value && this.left != null) {
                return this.left.selectByparent(val);
            } else if (val >= this.value && this.right != null) {
                return this.right.selectByparent(val);
            } else {
                return null;
            }
        }
    }


}
